package cn.b.sky.form.controller;

import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.form.constans.CustomerPageConstans;
import cn.b.sky.form.model.*;
import cn.b.sky.form.service.BusinessFieldService;
import cn.b.sky.form.service.BusinessTypeService;
import cn.b.sky.form.service.FormObjectService;
import cn.b.sky.form.service.ScreenService;
import cn.b.sky.user.controller.SecurityController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 
 * <strong>Title : PageController.java<br></strong>
 * <strong>Package : cn.b.sky.form.controller<br></strong>
 * <strong>Description : </strong>页面跳转控制器<br> 
 * <strong>Create on : 2016-11-9 下午5:53:58<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/form/*")
public class PageController extends SecurityController {

  @Resource
  private BusinessFieldService businessFieldService;

  @Resource
  private BusinessTypeService businessTypeService;

  @Resource
  private FormObjectService formObjectService;
  
  @Resource
  private ScreenService screenService;

  /**
   * 
   * <strong>Title : getCommonForm<br></strong>
   * <strong>Description : </strong>界面预览<br> 
   * <strong>Create on : 2016-12-15 下午2:15:13<br></strong>
   * <p>
   * @param model
   * @param formKey
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("/getFrom/{formKey}")
  public String getCommonForm(Model model, @PathVariable("formKey") String formKey) {
    //查询此form的元素
    Screen screen = screenService.getScreen(this.getSiteCode(), formKey);
    setBusinessFiledAndValueToScreen(screen);
    //放到model里进行数据处理
    model.addAttribute(CustomerPageConstans.SCREEN_PARAM, screen);
    return "screen/customForm_preview";
  }
  /**
   * 
   * <strong>Title : getCommonForm<br></strong>
   * <strong>Description : 获取用户配置的表单</strong><br> 
   * <strong>Create on : 2016-11-9 下午7:37:02<br></strong>
   * <p>
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("/getFrom/{formKey}/{bussinessKey}")
  public String getCommonForm(Model model, @PathVariable("formKey") String formKey,
                              @PathVariable("bussinessKey") String bussinessKey) {
    //查询此form的元素
    Screen screen = screenService.getScreen(this.getSiteCode(), formKey);
    setBusinessFiledAndValueToScreen(screen);
    BusinessType type = businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), screen.getBusinessType());
    if (type == null || type.getTableCreateFlag() != 1) {
      throw ImeException.newException("数据库表不存在");
    }
    //通过业务模型查询业务数据
    if (!StringUtils.isBlank(bussinessKey)) {
      List<Map<String, Object>> list = formObjectService.getFormObjectDataByBizId(this.getSiteCode(),
          type.getDbTable(), bussinessKey);
      if (list != null && list.size() > 0) {
        if (list.size() != 1) {
          throw ImeException.newException("查询数据多余一条");
        }
        Map<String, Object> map = list.get(0);
        setBusinessFieldValue(map, screen.getSections());
      }
    }
    //放到model里进行数据处理
    model.addAttribute(CustomerPageConstans.SCREEN_PARAM, screen);
    model.addAttribute(CustomerPageConstans.BUSINESSCODE, bussinessKey);
    return "screen/customForm_preview";
  }
  
  
  @RequestMapping("/startWorkFlow/{formKey}/{processdefinitionKey}")
  public String getStartWorkFlowForm(Model model, @PathVariable("formKey") String formKey,
                                     @PathVariable("processdefinitionId")String processdefinitionId) {
    //查询此form的元素
    Screen screen = screenService.getScreen(this.getSiteCode(), formKey);
    setBusinessFiledAndValueToScreen(screen);
    BusinessType type = businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), screen.getBusinessType());
    if (type == null || type.getTableCreateFlag() != 1) {
      throw ImeException.newException("数据库表不存在");
    }
    //放到model里进行数据处理
    model.addAttribute(CustomerPageConstans.SCREEN_PARAM, screen);
    //流程自定义表单key
    model.addAttribute(CustomerPageConstans.FORMKEY, formKey);
    //流程key
    model.addAttribute(CustomerPageConstans.PROCESSDEFINITIONID, processdefinitionId);
    return "screen/startFlowForm";
  }

  private void setBusinessFiledAndValueToScreen(Screen screen) {
    List<Section> sections = screen.getSections();
    
    if(sections != null && sections.size() > 0){
      for(Section section : sections){
        List<ScreenField> screenFields = section.getScreenField();
        setBusinessFiledAndValueToScreenField(screenFields);
      }
    }
    
  }

  private void setBusinessFiledAndValueToScreenField(List<ScreenField> screenFields) {
    if(screenFields != null && screenFields.size() > 0){
      for(ScreenField field : screenFields){
        //有可能为空，占位符，如果是占位符就不管了业务字段
        if(!StringUtils.isBlank(field.getBusinessField())){
          field.setBf(businessFieldService.getBusinessFieldAndValues(
              field.getSiteCode(), field.getBusinessType(), field.getBusinessField()));
        }else{
          //构造一个占位符的业务字段，虚拟的,为了满足占位符的设计，头大
          field.setBf(getPlaceholderBusinessFiled());
        }
      }
    }
    
  }


  /**
   * 
   * <strong>Title : getPlaceholderBusinessFiled<br></strong>
   * <strong>Description : </strong>获取空的占位符<br> 
   * <strong>Create on : 2016-11-18 下午2:46:07<br></strong>
   * <p>
   * @return
   * BusinessField
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private BusinessField getPlaceholderBusinessFiled() {
    BusinessField bf = new BusinessField();
    bf.setFieldType("placeholder");
    return bf;
  }


  /**
   * 
   * <strong>Title : setBusinessFieldValue<br></strong>
   * <strong>Description : </strong>给字段属性赋值<br> 
   * <strong>Create on : 2016-11-15 上午9:20:38<br></strong>
   * <p>
   * @param map
   * @param sections
   * void
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private void setBusinessFieldValue(Map<String, Object> map, List<Section> sections) {
    if (sections != null) {
      for (Section section : sections) {
        List<ScreenField> screenFields = section.getScreenField();
        if (screenFields != null && screenFields.size() > 0) {
          for (ScreenField field : screenFields) {
            BusinessField bf = field.getBf();
            if (bf != null && !StringUtils.isBlank(bf.getDbField())) {
              bf.setDefaultValue(convertData(bf.getDataType(), map.get(bf.getDbField().toUpperCase())));
            }
          }
        }
      }
    }

  }

  /**
   * 
   * <strong>Title : convertData<br></strong>
   * <strong>Description : 获取转换后的数据类型目前之处理日期类型，
   * 不考虑那么多，后面新数据类型出来再说</strong><br> 
   * <strong>Create on : 2016-11-15 上午9:37:43<br></strong>
   * <p>
   * @param dataType
   * @param object
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private String convertData(String dataType, Object value) {
    if(value != null){
      if(dataType.equalsIgnoreCase("date")){
        return DateUtils.getDateUtils(DateUtils.YYYY_MM_DD).format(value);
      }else if(dataType.equalsIgnoreCase("datetime")){
        return DateUtils.getDateUtils().format(value);
      }else{
        return value.toString();
      }
    }
    return "";
  }
}
